package cn.reone.mbt.connect;

import android.bluetooth.BluetoothSocket;
import android.os.Handler;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by wangxingsheng on 2017/3/6.
 */

public class ConnectedThread extends Thread{
    private final BluetoothSocket mmSocket;
    protected final InputStream mmInStream;
    protected final OutputStream mmOutStream;
    protected Handler mHandler;
    public static final int MESSAGE_READ = 200;

    public ConnectedThread(BluetoothSocket socket,Handler handler) {
        mmSocket = socket;
        mHandler = handler;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer;
        int bytes;
        while (true) {
            try {
                buffer = new byte[1024];
                bytes = mmInStream.read(buffer);
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
            mmOutStream.flush();
        } catch (IOException e) { }
    }

    public void cancel() {
        try {
            if(mmInStream!=null){
                mmInStream.close();
            }
            if(mmOutStream!=null){
                mmOutStream.close();
            }
            mmSocket.close();
        } catch (IOException e) { }
    }
}